package com.wyl.auth.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.wyl.auth.captcha.CaptchaService;
import com.wyl.auth.captcha.constant.CaptchaConst;
import com.wyl.auth.config.security.SecurityHolder;
import com.wyl.auth.config.security.SecurityUser;
import com.wyl.auth.entity.SysUser;
import com.wyl.auth.exception.BusinessException;
import com.wyl.auth.service.LoginService;
import com.wyl.auth.service.SysMenuService;
import com.wyl.auth.service.SysUserService;
import com.wyl.auth.util.BeanAwareUtil;
import com.wyl.auth.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2024/11/30 15:18
 */
@Service
public class UsernamePasswordLoginService implements LoginService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void doLogin(String username, String password,String code,boolean rememberMe) {
        if(StrUtil.isBlank(code) || !captchaService.validateCaptcha(code)) {
            throw new BusinessException(0,"验证码错误");
        }

        SysUserVo sysUserVo = loadUserByUsername(username);
        if(sysUserVo == null || !BCrypt.checkpw(password, sysUserVo.getPassword())) {
            throw new BusinessException(0,"帐号或密码错误");
        }
        StpUtil.login(sysUserVo.getId(),rememberMe);

        // 缓存用户权限
        applicationContext.publishEvent(sysUserVo.getId());
    }

    private SysUserVo loadUserByUsername(String username) {
        return  sysUserService.getByUsername(username);
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }
}